package org.qqcui.designpattern.patterns.proxy.cglib;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;
import java.util.Random;

/**
 * CGLIB动态代理类，需要实现 MethodInterceptor 接口，因为其是通过拦截器的机制来实现的
 *
 * @author cuiqingqiang
 * @version 1.0
 * @date 2022/5/1 10:34
 **/
public class ProxyFactory implements MethodInterceptor {

    private Object target;

    public ProxyFactory(Object target) {
        this.target = target;
    }

    public Object getProxyInstance() {
        // 创建一个增强对象
        Enhancer enhancer = new Enhancer();
        // 设置增强对象的一些属性
        enhancer.setSuperclass(target.getClass());
        // 调用自己的回调方法，也即是 intercept
        enhancer.setCallback(this);
        return enhancer.create();
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("CGLIB代理开始……");
        Object returnVal = method.invoke(target, objects);
        System.out.println("CGLIB代理提交……");
        return returnVal;
    }
}
